package com.pj.compose.ui.page.widget

import android.view.MotionEvent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.navigation.NavController
import com.pj.compose.ui.compose.AppTopBarColumn

@Composable
fun MyCanvasPage(navController: NavController) {
    AppTopBarColumn("MyCanvasPage", backClick = { navController.popBackStack() }) {
        Box(modifier = Modifier.fillMaxSize()) {
            MyCanvas()
        }
    }
 }

@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun MyCanvas() {
    //记录初始按下的点
    var downX by remember {
        mutableStateOf(0f)
    }
    var downY by remember {
        mutableStateOf(0f)
    }
    //绘制路径
    val path = Path()

    Box(modifier = Modifier.fillMaxSize(),contentAlignment = Alignment.BottomCenter) {
        Canvas(modifier = Modifier
            .fillMaxSize()
            //使用pointerInteropFilter来获取触摸事件
            .pointerInteropFilter { event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        //按下屏幕时，path移动到点击的地方
                        downX = event.x
                        downY = event.y
                        path.moveTo(downX, downY)
                    }
                    MotionEvent.ACTION_MOVE -> {
                        //手指移动时，绘制线条，并重置downX和downY
                        path.lineTo(downX, downY)
                        downX = event.x
                        downY = event.y
                    }
                }
                true
            }, onDraw = {
            //在这里使用一下这个变量，当downX发生变化时，进行recompose
            downX
            //把记录的path绘制出来
            drawPath(
                path,
                color = Color.Black,
                style = Stroke(width = 20f, cap = StrokeCap.Round, join = StrokeJoin.Round)
            )
        })

        //给画板添加清除的功能
        //在button的onClick事件中，调用path.reset()，再将downX置为0触发Canvas的recompose即可
        Button(onClick = {
            path.reset()
            downX = 0f
        }) {
            Text(text = "清除全部")
        }
    }
}
